import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter1911/bean/home_banner_bean_result.dart';
import 'package:flutter1911/bean/home_hot_goods_bean_result.dart';
import 'package:flutter1911/bean/home_navigator_bean_result.dart';
import 'package:flutter1911/bean/home_recommend_bean_result.dart';
import 'package:flutter1911/service/service.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter1911/router/application.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    _getHotGoods();
    super.initState();
  }

  int size = 10;
  List<HomeHotGoodsbean?>? hotGoodsList = [];

  //火爆专区的标题
  final Widget _hotTitle = Container(
    margin: const EdgeInsets.only(top: 10.0),
    padding: const EdgeInsets.all(5.0),
    alignment: Alignment.centerLeft,
    decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
    child: const Text(
      '火爆专区',
      style: TextStyle(color: Colors.pink),
    ),
  );

  //火爆专区的瀑布流List
  Widget _hotWarpList() {
    if (hotGoodsList!.isNotEmpty) {
      List<Widget> listItemWidget = hotGoodsList!.map((e) {
        return InkWell(
          onTap: () {
            Application.router!.navigateTo(context, '/detail?id = ${e!.id}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: const EdgeInsets.all(5.0),
            margin: const EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: [
                Image.network(
                  e!.goodsDefaultIcon!,
                  width: ScreenUtil().setWidth(375),
                ),
                Text(
                  e.goodsDesc!,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Text('团购价:¥${e.goodsDefaultPrice}元'),
                Text(
                  '原价:¥${e.goodsDefaultPrice}0元',
                  style: const TextStyle(
                      color: Colors.black26,
                      decoration: TextDecoration.lineThrough),
                ),
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listItemWidget,
      );
    } else {
      return const Center(
        child: Text('加载中...'),
      );
    }
  }

  //火爆专区的组合
  Widget _hotGoods() {
    return Container(
      child: Column(
        children: [_hotTitle, _hotWarpList()],
      ),
    );
  }

  void _getHotGoods() {
    var formData = '10';
    request('homeHotGoods', formData).then((value) {
      List<HomeHotGoodsbean?>? newList =
          HomeHotGoodsResult
              .fromJson(value)
              .data
              ?.list;
      setState(() {
        hotGoodsList!.addAll(newList!);
        formData = '15';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('百姓生活+'),
      ),
      body: EasyRefresh(
        onRefresh: () {},
        onLoad: () {
          _getHotGoods();
        },
        header: const ClassicHeader(
            backgroundColor: Colors.white,
            textStyle: TextStyle(color: Colors.pink),
            dragText: '下载刷新',
            armedText: '松开刷新',
            processedText: '刷新完成',
            readyText: '刷新中...',
        ),
        footer: const ClassicFooter(
          backgroundColor: Colors.white,
          textStyle: TextStyle(color: Colors.pink),
          dragText: '上拉加载',
          armedText: '松开加载',
          processedText: '加载完成',
          readyText: '加载中...',
        ),
        child: ListView(
          children: [
            FutureBuilder(
              future: request('homePageBanner', null),
              builder: (context, val) {
                if (val.hasData) {
                  List<HomeBannerBean> homeBannerBeanList =
                  HomeBannerBeanResult
                      .fromJson(val.data)
                      .data!;
                  return MySwiper(homeBannerBeanList: homeBannerBeanList);
                } else {
                  return const Center(
                    child: Text('加载中...'),
                  );
                }
              },
            ),
            FutureBuilder(
                future: request('homeNavigator', null),
                builder: (context, val) {
                  if (val.hasData) {
                    List<HomeNavigatorBean> homeNavigatorList =
                    HomeNavigatorBeanResult
                        .fromJson(val.data)
                        .data!;
                    return HomeNavigator(navigatorList: homeNavigatorList);
                  } else {
                    return const Center(
                      child: Text('加载中...'),
                    );
                  }
                }),
            FutureBuilder(
              builder: (context, val) {
                if (val.hasData) {
                  List<HomeRecommendBean?>? recommendList =
                      HomeRecommendBeanResult
                          .fromJson(val.data)
                          .data!
                          .list;
                  return Recommend(recommendList: recommendList);
                } else {
                  return const Center(
                    child: Text('加载中...'),
                  );
                }
              },
              future: request('homeRecommend', null),
            ),
            _hotGoods()
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

//轮播图控件
class MySwiper extends StatelessWidget {
  final List<HomeBannerBean> homeBannerBeanList;

  const MySwiper({Key? key, required this.homeBannerBeanList})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: ScreenUtil().setHeight(450),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount: homeBannerBeanList.length,
        itemBuilder: (context, index) {
          return Image.network(
            homeBannerBeanList[index].imagepath!,
            fit: BoxFit.fill, //代表图片全屏拉伸
          );
        },
        pagination: const SwiperPagination(), //控制轮播图的小圆点
        autoplay: true, //设置是否自动轮播
      ),
    );
  }
}

//导航栏控件
class HomeNavigator extends StatelessWidget {
  final List<HomeNavigatorBean> navigatorList;

  const HomeNavigator({Key? key, required this.navigatorList})
      : super(key: key);

  //girdViewItem的布局
  Widget _girdViewItemUI(context, HomeNavigatorBean item) {
    return InkWell(
      onTap: () {
        print('点击了导航:${item.id}');
      },
      child: Column(
        children: [
          Image.network(
            '${item.attienImage}',
            width: ScreenUtil().setWidth(95),
          ),
          Text('${item.attenName}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: const EdgeInsets.all(3.0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: const EdgeInsets.all(4.0),
        children: navigatorList.map((it) {
          return _girdViewItemUI(context, it);
        }).toList(), //拿到数据集合后,将它迭代(遍历),把其中的每一个数值赋值给item,再形成一个item的集合
      ),
    );
  }
}

//商品推荐的组件
class Recommend extends StatelessWidget {
  final List<HomeRecommendBean?>? recommendList;

  const Recommend({Key? key, required this.recommendList}) : super(key: key);

  //商品推荐的标题
  Widget _title() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.0, color: Colors.black12),
          )),
      child: const Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //商品推荐的item
  Widget _item(HomeRecommendBean item) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: const EdgeInsets.all(8.0),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
            Border(left: BorderSide(width: 1.0, color: Colors.black12))),
        child: Column(
          children: [
            Image.network(item.goodsDefaultIcon!),
            Text('¥${item.goodsDefaultPrice}元'),
            Text(
              '¥${item.goodsDefaultPrice}元',
              style: const TextStyle(
                  decoration: TextDecoration.lineThrough, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  //商品推荐横向列表组件
  Widget _recommendList() {
    return SizedBox(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        itemCount: recommendList!.length,
        itemBuilder: (context, index) {
          return _item(recommendList![index]!);
        },
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(385),
      margin: const EdgeInsets.only(top: 10.0),
      child: Column(
        children: [_title(), _recommendList()],
      ),
    );
  }
}
